package com.zifan.sever.config.swagger;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.RequestHandler;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.List;

/**
 * swagger2配置类
 * @author Zifan
 * @date 2021年04月10日20:40
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket createRestApi(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.zifan.sever.controller"))
                .paths(PathSelectors.any())
                .build()
                //需要给swagger加点东西，让他能全局登录
                .securityContexts(securityContexts())
                .securitySchemes(securitySchemes())
                ;
    }

    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("云E办-接口文档")
                .description("云E办-接口文档")
                .contact(new Contact("子凡","http://localhost:8081/doc.html","zifan1001@foxmail.com"))
                .version("1.0")
                .build();
    }

    private List<ApiKey> securitySchemes(){
        //用来设置请求头信息
        ArrayList<ApiKey> resList = new ArrayList<>();
        ApiKey apiKey = new ApiKey("Authorization","Authorization","Header");
        resList.add(apiKey);
        return resList;
    }

    private List<SecurityContext> securityContexts(){
        //设置需要认证的路径
        ArrayList<SecurityContext> resList = new ArrayList<>();
        resList.add(getContextByPath("/hello/.*"));
        return resList;
    }

    private SecurityContext getContextByPath(String s) {
        return SecurityContext.builder()
                .securityReferences(defaultAuth())
                .forPaths(PathSelectors.regex(s))
                .build();
    }

    private List<SecurityReference> defaultAuth() {
        ArrayList<SecurityReference> resList = new ArrayList<>();
        //授权范围
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        resList.add(new SecurityReference("Authorization",authorizationScopes));
        return resList;
    }

}
